package com.etung.iot.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.dao.AlarmInfoMapper;
import com.etung.iot.demo.modles.AlarmInfo;
import com.etung.iot.demo.runner.AlarmRunner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Handler(TopicConfig.ALARM_INFO_TOPIC)
@Slf4j
public class AlarmInfoHandler implements TopicHandler{
    @Autowired
    private AlarmInfoMapper alarmInfoMapper;


    @Override
    public void handler(String topic,String payload) {
        log.info("payload:"+payload);
        JSONObject jsonObject = JSONObject.parseObject(payload);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<AlarmInfo> alarmInfoList = Lists.newArrayList();
        String imei = "";
        Date time = null;
        if(jsonObject.containsKey("imei") && jsonObject.containsKey("time")){
            imei = jsonObject.getString("imei");
            time = new Date(jsonObject.getLong("time"));
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if(StringUtils.isNumeric(entry.getKey())){
                AlarmInfo alarmInfo = new AlarmInfo();
                alarmInfo.setAlarmId(Integer.parseInt(entry.getKey()));
                alarmInfo.setValue(String.valueOf(entry.getValue()));
                alarmInfo.setImei(imei);
                alarmInfo.setTime(time);
                alarmInfoList.add(alarmInfo);
                try {
                    AlarmRunner.queue.put(alarmInfo);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if(alarmInfoList.size() > 0){
            alarmInfoMapper.insertList(alarmInfoList);
        }
    }
}
